<?php

namespace App\Models;

use Encore\Admin\Traits\AdminBuilder;
use App\Models\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Request;

/**
 * Class Menu.
 */
class Menu extends Model
{
    use AdminBuilder, ModelTree;

    protected $table = 'admin_menu';

    /**
     * The attributes that are mass assignable.
     * @var array
     */
    protected $fillable = ['parent_id', 'order', 'title', 'icon', 'uri', 'permission','backend'];

    public function __construct($backend='')
    {
		if($backend){
			static::addGlobalScope('avaiable',function(Builder $builder) use($backend){
				$builder->where('backend',$backend);
			});
		}
        parent::__construct();
    }

 
    /**
     * {@inheritdoc}
     */
    public function delete()
    {
        $ids = $this->getnodeids($this->getKey(),'backend');
		if($ids && count($ids)>1){
			unset($ids[0]);
			if($ids) $this->whereIn('id',$ids)->delete();
		}
        return parent::delete();
    }

    
    /**
     * A Menu belongs to many roles.
     *
     * @return BelongsToMany
     */
    public function roles() : BelongsToMany
    {
        $pivotTable = config('admin.database.role_menu_table');

        $relatedModel = config('admin.database.roles_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'menu_id', 'role_id');
    }

    /**
     * @return array
     */
    public function allNodes() : array
    {
        $connection = config('admin.database.connection') ?: config('database.default');
        $orderColumn = DB::connection($connection)->getQueryGrammar()->wrap($this->orderColumn);

        $byOrder = $orderColumn.' = 0,'.$orderColumn;

        $query = static::query();

        if (config('admin.check_menu_roles') !== false) {
            $query->with('roles');
        }

        return $query->orderByRaw($byOrder)->get()->toArray();
    }

    /**
     * determine if enable menu bind permission.
     *
     * @return bool
     */
    public function withPermission()
    {
        return (bool) config('admin.menu_bind_permission');
    }

	public function removeCache($backend='')
    {		
		if(empty($backend)){
			foreach(get_backends() as $backend){
				\Cache::forget('sys_table_menus_'.$backend);
			}
		}elseif(!empty($xapp)){
			\Cache::forget('sys_table_menus_'.$backend);
		}
    }
}
